import { ModalForm, ProFormDatePicker } from '@ant-design/pro-form';
import { Column } from '@ant-design/charts';
import { Card, Descriptions, message, Tag } from 'antd';
import moment from 'moment';
import { useCallback, useEffect, useState } from 'react';
import { getSimInfo, getSimUsage, updateIotSimFlowInfo } from '../service';
import type { DahanSimInfo, IotSimTableListItem, TibiotSimInfo, UpiotSimInfo } from '../typings';
import ConfirmModal from '@/components/ConfirmModal';

const mapSupplier = new Map()
  .set('CMCC', '中国移动')
  .set('CTCC', '中国电信')
  .set('CUCC', '中国联通');
const mapDevice = new Map()
  .set(0, '视频巡检车')
  .set(1, 'GPS设备')
  .set(2, '4G车位锁')
  .set(3, '4G流量主机')
  .set(4, '诱导屏控制卡')
  .set(99, '其他设备');

const SimInfoModal = (props: {
  simItem: IotSimTableListItem;
  visible: boolean;
  hideModalVisible: () => void;
}) => {
  const { simItem, visible, hideModalVisible } = props;
  const { iccid, provider, supplier, pkgExpiredTime, deviceType, _id } = simItem;
  const [upiotSimData, setUpiotSimData] = useState<UpiotSimInfo>();
  const [dahanSimData, setDahanSimData] = useState<DahanSimInfo>();
  const [tibiotSimData, setTibiotSimData] = useState<TibiotSimInfo>();
  const [date, setDate] = useState<string>();
  const [usageLogData, setUsageLogData] = useState<{ value: number; time: string }[]>([]);

  const reloadCardInfo = useCallback((ic: string, pi: string) => {
    getSimInfo(ic, pi).then((res) => {
      if (res?.success && res.data) {
        if (provider === 'upiot' && res.data) {
          setUpiotSimData(res.data as UpiotSimInfo);
        } else if (provider === 'dahan' && res.data) {
          setDahanSimData(res.data as DahanSimInfo);
        } else if (provider === 'tibiot' && res.data) {
          setTibiotSimData(res.data as TibiotSimInfo);
        }
      } else {
        message.error({ content: `获取卡信息失败, ${res.message}`, key: 'simInfo' });
      }
    });
  }, []);
  const reloadUsage = useCallback((ic: string, pi: string, da: string) => {
    getSimUsage(ic, pi, da).then((res) => {
      if (res.success) {
        if (res.data) setUsageLogData(res.data || []);
      } else {
        message.error({ content: `获取卡日流量失败, ${res.message}`, key: 'simUsage' });
      }
    });
  }, []);
  useEffect(() => {
    // getSimInfo(iccid, provider).then((res) => {
    //   if (res?.success && res.data) {
    //     if (provider === 'upiot' && res.data) {
    //       setUpiotSimData(res.data as UpiotSimInfo);
    //     } else if (provider === 'dahan' && res.data) {
    //       setDahanSimData(res.data as DahanSimInfo);
    //     } else if (provider === 'tibiot' && res.data) {
    //       setTibiotSimData(res.data as TibiotSimInfo);
    //     }
    //   } else {
    //     message.error({ content: `获取卡信息失败, ${res.message}`, key: 'simInfo' });
    //   }
    // });
    reloadCardInfo(iccid, provider);
  }, [iccid, provider]);

  useEffect(() => {
    reloadUsage(iccid, provider, date || moment().format('YYYY-MM-DD'));
  }, [date, iccid, provider]);

  const disabledDate = (current: any) => {
    if (!current) return true;
    const outOfToday = current > moment().endOf('day');
    return outOfToday;
  };

  const renderUpiotCardStatus = (status: string) => {
    switch (status) {
      case '00':
        return <Tag color="green">使用中</Tag>;
      case '10':
        return <Tag color="green">测试期</Tag>;
      case '02':
        return <Tag color="red">已停机</Tag>;
      case '03':
        return <Tag color="red">预销号</Tag>;
      case '04':
        return <Tag color="pink">已销号</Tag>;
      case '11':
        return <Tag color="green">沉默期</Tag>;
      case '12':
        return <Tag color="red">停机保号</Tag>;
      case '99':
      default:
        return <Tag color="purple">未知</Tag>;
    }
  };
  const renderTibiotCardStatus = (status: string) => {
    switch (status) {
      case '1':
        return <Tag color="green">正常</Tag>;
      case '2':
        return <Tag color="red">停机</Tag>;
      case '3':
        return <Tag color="blue">待激活</Tag>;
      default:
        return <Tag color="purple">未知</Tag>;
    }
  };

  return (
    <ModalForm
      width="68vw"
      title={
        <>
          卡号 - {iccid}{' '}
          <ConfirmModal
            type="button"
            btnText="点击更新卡信息"
            titleText="更新流量信息"
            text="更新流量信息后，会重新获取卡的日流量信息，更新到数据库中，以便于后续的流量统计。"
            operFunc={async () => await updateIotSimFlowInfo(_id)}
            reload={() => {
              reloadCardInfo(iccid, provider);
              reloadUsage(iccid, provider, date || moment().format('YYYY-MM-DD'));
            }}
          />
        </>
      }
      modalProps={{
        destroyOnClose: true,
        bodyStyle: {
          padding: '10px 40px 48px',
        },
        onCancel: () => hideModalVisible(),
      }}
      visible={visible}
      submitter={false}
    >
      {upiotSimData && (
        <Card title="基本信息">
          <Descriptions>
            <Descriptions.Item label="卡供应商">上海量讯</Descriptions.Item>
            <Descriptions.Item label="设备类型">{mapDevice.get(deviceType)}</Descriptions.Item>
            <Descriptions.Item label="运营商">{mapSupplier.get(supplier)}</Descriptions.Item>
            <Descriptions.Item label="短信下发">
              {upiotSimData.support_sms ? '支持' : '不支持'}
            </Descriptions.Item>
            <Descriptions.Item label="当前状态">
              {renderUpiotCardStatus(upiotSimData.account_status)}
            </Descriptions.Item>
            <Descriptions.Item label="激活时间">{upiotSimData.active_date}</Descriptions.Item>
            <Descriptions.Item label="到期时间">{upiotSimData.expiry_date}</Descriptions.Item>
            <Descriptions.Item label="套餐大小">{upiotSimData.data_plan} MB</Descriptions.Item>
            <Descriptions.Item label="当月流量">{upiotSimData.data_usage} MB</Descriptions.Item>
            <Descriptions.Item label="剩余流量">{upiotSimData.data_balance} MB</Descriptions.Item>
          </Descriptions>
        </Card>
      )}
      {dahanSimData && (
        <Card title="基本信息">
          <Descriptions>
            <Descriptions.Item label="卡供应商">大汉三通</Descriptions.Item>
            <Descriptions.Item label="设备类型">{mapDevice.get(deviceType)}</Descriptions.Item>
            <Descriptions.Item label="运营商">{mapSupplier.get(supplier)}</Descriptions.Item>
            <Descriptions.Item label="短信下发" span={2}>
              {dahanSimData.smsAbility === '1' ? '支持' : '不支持'}
            </Descriptions.Item>
            <Descriptions.Item label="激活时间">{dahanSimData.activeTime}</Descriptions.Item>
            <Descriptions.Item label="失效时间">
              {moment(pkgExpiredTime).format('YYYY-MM-DD')}
            </Descriptions.Item>
            <Descriptions.Item label="套餐名称">
              {dahanSimData.flowPackage[0]?.pkgName}
            </Descriptions.Item>
          </Descriptions>
        </Card>
      )}
      {tibiotSimData && (
        <Card title="基本信息">
          <Descriptions>
            <Descriptions.Item label="卡供应商">上海齐犇</Descriptions.Item>
            <Descriptions.Item label="设备类型">{mapDevice.get(deviceType)}</Descriptions.Item>
            <Descriptions.Item label="运营商">{mapSupplier.get(supplier)}</Descriptions.Item>
            <Descriptions.Item label="当前状态">
              {renderTibiotCardStatus(tibiotSimData.cardStatus)}
            </Descriptions.Item>
            <Descriptions.Item label="激活时间">{tibiotSimData.activateTime}</Descriptions.Item>
            <Descriptions.Item label="到期时间">{tibiotSimData.packageTime}</Descriptions.Item>
            <Descriptions.Item label="套餐名称">{tibiotSimData.packageName}</Descriptions.Item>
            <Descriptions.Item label="套餐大小">{tibiotSimData.totalFlow}</Descriptions.Item>
            <Descriptions.Item label="已用流量">{tibiotSimData.cardFlow}</Descriptions.Item>
          </Descriptions>
        </Card>
      )}
      {!dahanSimData && !upiotSimData && !tibiotSimData && (
        <div>
          <h3>无法查询到此卡信息</h3>
        </div>
      )}
      <Card
        title="日流量统计"
        extra={
          provider !== 'tibiot' && (
            <div>
              <span>选择月份: </span>
              <ProFormDatePicker
                fieldProps={{
                  disabledDate,
                  picker: 'month',
                  format: 'YYYY-MM',
                  defaultValue: moment(),
                  onChange: (_, dateString) => setDate(dateString),
                }}
                allowClear={false}
              />
            </div>
          )
        }
        style={{ marginTop: 20 }}
      >
        <div>
          <Column
            data={usageLogData}
            padding="auto"
            xField="time"
            yField="value"
            meta={{
              value: { alias: '流量(MB)' },
              time: { alias: '日期' },
            }}
            // yAxis={{ title: { text: '流量(MB)', position: 'end', autoRotate: false } }}
          />
        </div>
      </Card>
    </ModalForm>
  );
};

export default SimInfoModal;
